<?php
/**
 *+------------------
 * madong
 *+------------------
 * Copyright (c) https://gitee.com/motion-code  All rights reserved.
 *+------------------
 * Author: Mr. April (405784684@qq.com)
 *+------------------
 * Official Website: http://www.madong.tech
 */

namespace madong\webman\wf\services;

use madong\webman\wf\basic\BaseService;
use madong\helper\Pagination;
use madong\helper\PropertyCopier;
use madong\ingenious\interface\model\IProcessType;
use madong\ingenious\interface\services\IProcessTypeService;
use madong\ingenious\libs\utils\ArrayHelper;
use madong\ingenious\libs\utils\AssertHelper;
use madong\webman\wf\dao\ProcessTypeDao;

class ProcessTypeService extends BaseService implements IProcessTypeService
{

    public function __construct()
    {
        $this->dao = new ProcessTypeDao();
    }

    public function created(object $param): ?IProcessType
    {
        unset($param->id);
        $model = $this->dao->getModel();
        PropertyCopier::copyProperties($param, $model);
        return $this->dao->save($model->toArray());
    }

    public function del(string|array|int $data): array
    {
        return $this->transaction(function () use ($data) {
            $data       = ArrayHelper::normalize($data);
            $deletedIds = [];
            foreach ($data as $id) {
                $item = $this->dao->get($id);
                if (!$item) {
                    continue; // 如果找不到项，跳过
                }
                $item->delete();//删除主表
                $primaryKey   = $item->getPk();
                $deletedIds[] = $item->{$primaryKey};
            }
            return $deletedIds;
        });
    }

    public function updated(object $param): bool
    {
        AssertHelper::notNull($param->id ?? '', '参数ID不能为空');
        $model = $this->dao->get($param->id);
        PropertyCopier::copyProperties($param, $model);
        return $model->save();
    }

    public function list(object $param): array
    {
        $where = ArrayHelper::normalize(ArrayHelper::paramsFilter($param, [
            ['name'],
            ['enabled'],
            ['pid'],
        ]));

        [$page, $limit] = Pagination::getPageValue($param);
        $items = $this->dao->selectList($where, '*', $page, $limit, 'sort desc', ['parent'], true);
        $total = $this->dao->count($where, true);
        return compact('items', 'total');
    }

    public function listByType(object $param): array
    {
        $where = ArrayHelper::paramsFilter($param, [
            ['name', ''],
            ['enabled', 1],
            ['pid', 0],
        ]);
        [$page, $limit] = Pagination::getPageValue($param);
        return $this->dao->selectList($where, '*', $page, $limit, 'sort desc', ['parent', 'items'], true)->toArray();
    }

    public function findById(string|int $id): ?IProcessType
    {
        return $this->dao->get($id, ['*'], ['parent']);
    }
}
